package com.bookmall.cart.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipaySignature;
import com.bookmall.cart.config.AlipayTemplate;
import com.bookmall.cart.domain.vo.PayAsyncVo;
import com.bookmall.cart.service.IOrderInfoService;
import com.ruoyi.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description:
 * @Author 胡菜鸡
 * @Create 2022-04-28-14:00
 */
@RestController
public class OrderPayedListener {
    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    /**
     * 支付宝订单完成后，让其调用此接口
     * @author 胡菜鸡
     * @date 2022/4/28 14:00
     * @return success 表示收到了支付宝支付完成的通知
     */
    @PostMapping("/payed/notify")
    public String handleAlipayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        //验签
        Map<String,String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        Iterator<String> iter = requestParams.keySet().iterator();
        while(iter.hasNext()){
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for(int i = 0; i < values.length; i ++){
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时候使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //使用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type());
        if(signVerified){
            //签名验证成功
            System.out.println("签名验证成功");
            String result = "fail";
            try {
                result = orderInfoService.handlePayResult(payAsyncVo);
            } catch (ServiceException e) {
                e.printStackTrace();
            }
            return result;
        } else {
            //签名验证失败
            System.out.println("签名验证失败");
            return "fail";
        }
    }

}
